package com.project.systemfront.controller;

import com.project.systemfront.common.Result;
import com.project.systemfront.pojo.ForUser;
import com.project.systemfront.pojo.dto.LoginDto;
import com.project.systemfront.service.IForUserService;
import com.project.systemfront.utils.JwtUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/auth")
public class LoginController {

    @Autowired
    private IForUserService froUserService;

    @PostMapping("/login")
    public Result login(@RequestBody LoginDto loginDto){
        ForUser u=froUserService.findByUserName(loginDto.getUsername());
        if(u!=null){
            if(u.getPassword().equals(loginDto.getPassword())){
                Map<String,Object> claims=new HashMap<>();
                claims.put("id",u.getId());
                claims.put("username",u.getUsername());
                String token= JwtUtil.genToken(claims);
                return Result.success(token);
            }else{
                return Result.error(500,"密码错误");
            }
        }
        return Result.error(500,"用户不存在");


    }

    @PostMapping("/register")
    public Result register(@RequestBody LoginDto loginDto){
        ForUser u=froUserService.findByUserName(loginDto.getUsername());
        if(u==null){
            ForUser user=new ForUser();
            user.setUsername(loginDto.getUsername());
            user.setPassword(loginDto.getPassword());
            user.setNickname(loginDto.getNickname());
            user.setStatus(1L);
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            user.setUserType(0L);
            user.setNickname("用户"+loginDto.getUsername());
            froUserService.insertForUser(user);
            return Result.success("注册成功");
        }
        return Result.error(500,"用户已存在");
    }
}
